package com.bkaka.controller;

import com.bkaka.bean.ResponseBean;
import com.bkaka.email.EmailService;
import com.bkaka.entity.ExamUser;
import com.bkaka.entity.ExamUserCode;
import com.bkaka.service.ExamUserCodeServer;
import com.bkaka.service.ExamUserService;
import com.bkaka.util.code.CodeUtilService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.validation.Valid;

/**
 * Created by maxiaoqiang on 2018/7/27.
 */
@RestController
@RequestMapping(value = "${api.path}")
public class ExamUserCodeController {

    @Autowired
    private ExamUserService userService;

    @Autowired
    private ExamUserCodeServer userCodeServer;

    @Autowired
    private EmailService emailService;

    @Autowired
    private CodeUtilService codeUtilService;

    @PostMapping(value = "/sendcode", produces = "application/json;charset=UTF-8")
    public ResponseBean sendCode(@Valid @RequestBody ExamUserCode userCode) {

        String username = userCode.getUserName();
        // 查看用户是否已经存在
        ExamUser user = userService.findByUserName(username);
        if (user == null) { // 用户不存在时

            // 生成6位数字邮箱验证码
            String code = codeUtilService.createCode(6);

            // 检查是否发送过验证码
            ExamUserCode examUserCode = userCodeServer.findByNameCode(username);
            if (examUserCode != null) {
                userCodeServer.update(examUserCode.getId(), code);
            } else {
                userCode.setCode(code);
                // 存储邮箱验证码未后续对比
                userCodeServer.create(userCode);
            }
            // 发送邮箱验证码
//            emailService.sendSimpleMail(username, "在线考试账户注册", code);
            return new ResponseBean(200, "验证码已发送", null);
        } else { //用户存在时
            return new ResponseBean(501, "邮箱已存在", null);
        }
    }

}
